package com.cupk.services;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cupk.dtos.JwtResponse;
import com.cupk.dtos.RegisterRequest;
import com.cupk.dtos.ResetPasswordRequest;
import com.cupk.entities.User;
import com.cupk.exceptions.ResourceAlreadyExistsException;
import com.cupk.exceptions.ResourceNotFoundException;
import com.cupk.mapper.UserMapper; // 【修改】: 导入 UserMapper
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class AuthService {

    private final UserMapper userMapper; // 【修改】: 注入 UserMapper 而不是 UserRepository
    private final PasswordEncoder passwordEncoder;
    private final EmailService emailService;

    // 缓存定义保持不变
    private final Cache<String, String> registrationCodeCache = CacheBuilder.newBuilder()
            .expireAfterWrite(5, TimeUnit.MINUTES)
            .build();

    private final Cache<String, String> passwordResetCodeCache = CacheBuilder.newBuilder()
            .expireAfterWrite(5, TimeUnit.MINUTES)
            .build();

    // --- 辅助方法，用于替代原有的 Repository 方法 ---
    private boolean userExistsByEmail(String email) {
        // 使用 QueryWrapper 构造查询条件
        return userMapper.exists(new QueryWrapper<User>().eq("email", email));
    }

    private boolean userExistsByUsername(String username) {
        return userMapper.exists(new QueryWrapper<User>().eq("username", username));
    }

    // --- 注册相关方法 (已修改) ---

    public void sendRegistrationCode(String email) {
        if (userExistsByEmail(email)) { // 调用新的辅助方法
            throw new ResourceAlreadyExistsException("错误：该邮箱已被注册。");
        }
        String code = generateRandomCode();
        registrationCodeCache.put(email, code);
        emailService.sendVerificationCode(email, code);
    }

    @Transactional
    public void registerUser(RegisterRequest registerRequest) {
        String storedCode = registrationCodeCache.getIfPresent(registerRequest.getEmail());
        if (storedCode == null || !storedCode.equals(registerRequest.getVerificationCode())) {
            throw new IllegalArgumentException("邮箱验证码不正确或已过期。");
        }
        registrationCodeCache.invalidate(registerRequest.getEmail());

        if (userExistsByUsername(registerRequest.getUsername())) { // 调用新的辅助方法
            throw new ResourceAlreadyExistsException("错误：用户名 '" + registerRequest.getUsername() + "' 已被占用。");
        }

        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setEmail(registerRequest.getEmail());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
        user.setFullName(registerRequest.getFullName());
        user.setDepartment(registerRequest.getDepartment()); // 设置部门
        user.setPhoneNumber(registerRequest.getPhoneNumber()); // 设置手机号码
        user.setRole(registerRequest.getRole());
        // 设置默认状态为IDLE（空闲）
        user.setStatus("IDLE");

        // 使用 mapper.insert() 来保存新用户
        // 时间戳会由我们的 MyMetaObjectHandler 自动填充
        userMapper.insert(user);
    }

    // --- 密码重置相关方法 (已修改) ---

    public void sendPasswordResetCode(String email) {
        // 先检查邮箱是否存在
        if (userExistsByEmail(email)) {
            String code = generateRandomCode();
            passwordResetCodeCache.put(email, code);
            emailService.sendVerificationCode(email, code);
        }
        // 如果不存在，静默处理
    }

    @Transactional
    public void resetPassword(ResetPasswordRequest request) {
        String storedCode = passwordResetCodeCache.getIfPresent(request.getEmail());
        if (storedCode == null || !storedCode.equals(request.getVerificationCode())) {
            throw new IllegalArgumentException("验证码不正确或已过期。");
        }

        // 使用 mapper.selectOne() 查找用户
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("email", request.getEmail()));
        if (user == null) {
            throw new ResourceNotFoundException("未找到与该邮箱关联的用户。");
        }

        user.setPassword(passwordEncoder.encode(request.getNewPassword()));

        // 使用 mapper.updateById() 更新用户信息
        // 时间戳会由我们的 MyMetaObjectHandler 自动填充
        userMapper.updateById(user);

        passwordResetCodeCache.invalidate(request.getEmail());
    }

    private String generateRandomCode() {
        return String.valueOf(100000 + new Random().nextInt(900000));
    }

    public JwtResponse buildLoginResponse(String username, String jwt) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            throw new ResourceNotFoundException("登录成功后无法找到用户信息，用户: " + username);
        }

        return new JwtResponse(
                jwt,
                user.getId(),
                user.getUsername(),
                user.getEmail(),
                user.getRole(),
                user.getFullName(),      // 新增
                user.getPhoneNumber(),   // 新增
                user.getDepartment(),    // 新增
                null // user.getAvatarUrl() // 新增 (等头像功能实现后再填充)
        );
    }
}